<template>
    <div class="orderConfirm">
        <div v-html="aliPayHtml"></div>
        <van-nav-bar title="确认订单" left-arrow @click-left="$navBack(`/goods/goodsDetail?goodsId=${goodsId}`)"></van-nav-bar>
        <order-address-select @change="getExpressId"></order-address-select>
        <div v-for="(item, index) in orders" :key="index" class="list-wrap-pk list-item-pk item-content-pk orderInfo">
            <div>
                <van-icon class-prefix="pk-icon" name="commodity_business" size="15" color="#D82D11"></van-icon>
                <span style="padding-left: 10px">{{item.shopName}}</span>
            </div>
            <div class="d-flex-pk item-content-pk">
                <div class="itemLeft">
                    <pk-img :src="item.picture" class="goodsThumb"></pk-img>
                </div>
                <div class="flex-1">
                    <div>{{item.goodsName}}</div>
                    <div class="text-gray-b3-pk">规格：{{item.attrStr}}</div>
                </div>
                <div class="text-red-pk">￥{{item.price}}</div>
            </div>
            <div class="d-flex-cpb-pk item-content-pk">
                <div class="itemLeft">数量</div>
                <van-stepper
                        v-model="item.attrNum"
                        class="Stepper"
                        @change="goodsNumAdd"
                        button-size="20px"
                        input-width="60px">
                </van-stepper>
            </div>
            <div class="d-flex-pk item-content-pk">
                <div class="itemLeft">运费</div>
                <div class="flex-1">{{shippingCost}}</div>
            </div>
            <div class="d-flex-cpb-pk item-content-pks">
                <div class="itemLeft">订单备注</div>
                <van-field v-model="orderMark" placeholder="选填，请和商家协商一致" class="flex-1" />
            </div>
            <div class="text-right-pk">
                <span class="text-gray-b3-pk">共计{{item.attrNum}}件 &nbsp;&nbsp;</span>
                小计
                <span class="font-size-12-pk text-red-pk">￥</span>
                <span class="text-red-pk">{{$util.moneyFmt(item.attrNum*item.price)}}</span>
            </div>
        </div>
        <pay-type @change="getPayType"></pay-type>
        <pay-action class="p-fix-b-pk" :money="payMoney" @change="handlePay"></pay-action>
        <pay-password ref="payPasswordPop"  operate-type="1" @change="balancePay"></pay-password>
        <van-popup v-model="wxPayResult" closeable round>
            <div class="pk-popup-wrap text-center-pk">
                <div class="title">
                    请确认微信支付是否完成
                </div>
                <div class="payResult success text-red-pk" @click="wxPayResultConfirm('success')">
                    已完成支付
                </div>
                <div class="payResult fail"  @click="wxPayResultConfirm('fail')">
                    支付遇到问题
                </div>
            </div>
        </van-popup>
    </div>
</template>

<script>
    import PkImg from "../../components/PkImg";
    import OrderAddressSelect from "../../components/OrderAddressSelect";
    import PayType from "../../components/pay/payType";
    import PayAction from "../../components/pay/payAction";
    import PayPassword from "../../components/pay/PayPassword";
    export default {
        name: "orderConfirm",
        components: {PayPassword, PayAction, PayType, OrderAddressSelect, PkImg},
        data() {
            return {
                aliPayHtml: "",
                isDefaultAddress: false,
                orders: this.$store.state.orderInfo,
                goodsId: this.$route.query.goodsId,
                shopId: this.$route.query.shopId,
                expressId: "",
                orderMark: "",
                shippingCost: "",
                payType: "",
                payMoney: "",
                payPassword: "",
                dynamicSecretKey: {},//动态密钥
                orderIdList: [],//订单id 列表，
                wxPayResult: false
            }
        },

        created() {

        },
        beforeRouteLeave (to, from, next) {
            // 如果下一个页面不是要返回缓存的，则取消该页面的缓存
            if (to.name !== 'addressList') {
                this.$store.commit('keepAliveDelete', from.name)
            }
            next()
        },
        computed: {
            attrStr() {
                let tempArr = [];
                for(let key in this.attrData) {
                    if(!(key === "id" || key === "price" || key === "stock_num")) {
                        tempArr.push(this.attrData[key])
                    }
                }
                return tempArr.join("、")
            },
        },
        watch: {},
        methods: {
            getExpressId(val) {
                this.expressId = val;
                this.getShippingCost()
            },
            //获取运费
            getShippingCost() {
                this.$api.shippingCost({
                    orderShippingInfoList: [
                        {
                            expressId: this.expressId,
                            orderGoodsShippingList: this.orders.map(item => {
                                return {
                                    attrNum: item.attrNum,
                                    goodsId: item.goodsId
                                }
                            }),
                            shopId: this.shopId
                        }
                    ]
                }).then(res => {
                    let result = this.$resData(res);
                    if(result) {
                        this.shippingCost = result[0].shippingCost
                    }
                    this.getPayMoney()
                })
            },
            getPayType(val) {
                this.payType = val;
            },
            //增加数量
            async goodsNumAdd() {
                await this.getPayMoney();
                await this.getShippingCost();
            },
            getPayMoney() {
                let money = 0;
                this.orders.forEach(item => {
                    money = money + this.$util.moneyFmt(item.attrNum*item.price)
                });
                this.payMoney = money + this.$util.moneyFmt(this.shippingCost)
            },
            /*
             * 支付流程：获取动态密钥 -> 创建订单 -> 支付 -> 余额 ？ 支付结果 ： 转第三方支付
             */
            async handlePay(val) {
                if(!this.payType) {
                    this.$toast("请选择支付方式");
                    return false
                }
                //创建订单
                this.dynamicSecretKey = val;
                let orders = await this.goodsOrderCreate();
                if(!orders) {
                    return
                }
                this.orderIdList = orders.orderInfoVoList.map( item => {
                    return item.orderId
                });
                //判断|支付方式
                if(this.payType === "3") {
                    //余额支付
                    this.$refs.payPasswordPop.open()
                }else {
                    //第三方支付
                    this.goodsOrderPay()
                }
            },

            //创建订单
            goodsOrderCreate() {
                let orderGoodsInfoList = this.orders.map(item => {
                    return {
                        attrId: item.attrId,
                        attrNum: item.attrNum,
                        goodsId: item.goodsId,
                        receiveId: this.$store.state.receiveId || "",
                        userInviteNum: this.$store.state.inviteNum || ""
                    }
                });
                return new Promise( (resolve, reject) => {
                    this.$api.goodsOrderCreate({
                        orderInfoList: {
                            expressId: this.expressId,
                            orderGoodsInfoList: orderGoodsInfoList,
                            remark: this.orderMark,
                            shopId: this.shopId
                        },
                        payType: this.payType,
                    }).then(res => {
                        resolve(this.$resData(res))
                    }).catch( () => {
                        reject(false)
                    })
                })
            },
            //余额支付,输入密码
            balancePay(val) {
                this.payPassword = this.$util.encrypt(val, this.dynamicSecretKey.tokenKey);
                this.goodsOrderPay()
            },

            //支付 1支付宝支付 2微信支付 3余额支付 4银联支付
            //微信支付类型，不填默认app支付，0=App支付 1=H5支付 2=JSAPI支付
            goodsOrderPay() {
                this.$toast.loading("提交中");
                this.$api.goodsOrderPay({
                    aliPayType: "1",
                    orderIdList: this.orderIdList,
                    payType: this.payType,
                    userKey: this.dynamicSecretKey.userKey,
                    wxPayType: this.$global.isWxBrowser ? "2" : "1",
                    payPassword: this.payPassword,//余额支付需要输入支付密码
                }).then(res => {
                    this.$toast.clear();
                    let result = this.$resData(res);
                    if(result) {
                        switch (this.payType) {
                            case "1":
                                //支付宝
                                this.aliPay(result);
                                break;
                            case "2":
                                this.wxPay(result);
                                break;
                            case "3":
                                //余额
                                this.$toast.success("支付成功");
                                this.$router.push({path: "/goodsOrder/paySuccess", query: {orderId: this.orderIdList}});
                                break;
                        }
                    }
                })
            },

            //微信支付
            wxPay(result) {
                //微信,还应该判断是否在微信浏览器环境
                if(this.$global.isWxBrowser) {
                    this.onBridgeReady(result.wxUnifiedOrderVo);
                }else {
                    window.location.href = result.wxUnifiedOrderVo.mwebUrl;
                    setTimeout( () => {
                        this.wxPayResult = true;
                    },700);
                }
            },
            onBridgeReady(wxUnifiedOrderVo) {
                window.WeixinJSBridge.invoke(
                    'getBrandWCPayRequest', {
                        "appId":   wxUnifiedOrderVo.appid,   //公众号名称，由商户传入
                        "timeStamp": wxUnifiedOrderVo.timeStamp,         //时间戳，自1970年以来的秒数
                        "nonceStr": wxUnifiedOrderVo.noncestr, //随机串
                        "package": wxUnifiedOrderVo.packageStr,
                        "signType": wxUnifiedOrderVo.signType,      //微信签名方式：
                        "paySign": wxUnifiedOrderVo.sign //微信签名
                    },
                    function(res){
                        alert("再请求一次后端，判断订单支付状态,代完善");
                        //再请求一次后端，判断订单支付状态
                        if(res.err_msg == "get_brand_wcpay_request:ok" ){
                            // 使用以上方式判断前端返回,微信团队郑重提示：
                            //res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
                            this.$router.push({path: "/goodsOrder/paySuccess", query: {orderId: this.orderIdList}})
                        }
                    }
                )
            },

            wxPayResultConfirm(type) {
                //type success 成功 fail 失败
                this.wxPayResult = false;
                if(type === "success") {
                    this.$router.push({path: "/goodsOrder/paySuccess", query: {orderId: this.orderIdList}})
                }else {
                    if(this.orderIdList.length >1) {
                        this.$router.push({path: "/orderList"})
                    }else {
                        this.$router.push({path: "/orderDetail", query: {orderId: this.orderIdList[0] }})
                    }
                }
            },

            //支付宝支付
            aliPay(result) {
                //console.log(result.aliUnifiedOrderVo.aliPayBody)
                this.aliPayHtml = result.aliUnifiedOrderVo.aliPayBody;
                this.$nextTick( ()=> {
                    document.forms[0].submit();
                })
            }
        }
    }
</script>

<style lang="scss" scoped>
    .orderConfirm {
        padding-bottom: 70px;
        /deep/.van-cell__left-icon {
            color: var(--red-color);
        }
        .defaultAddress {
            padding: 10px;
            font-size: 14px;
        }
        .orderInfo {
            .itemLeft {
                width: 90px;
                text-align: right;
                padding-right: 10px;
            }
            /deep/.goodsThumb {
                img {
                    width: 88px;
                    height: 88px;
                }
            }
        }
        .pk-popup-wrap {
            padding: 15px 0 0;
            .payResult {
                padding: 15px;
            }

            .success {
                border-top: 1px solid #f5f5f5;
                border-bottom: 1px solid #f5f5f5;
            }
        }
    }
</style>
